package icerts

import (
	"gitee.com/djaf/my-certs/app/classes/certificates"
	"gitee.com/djaf/my-certs/app/data/database"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/data/entity"
	"github.com/starter-go/security/random"
	"gorm.io/gorm"
)

// CertificateDaoImpl ...
type CertificateDaoImpl struct {

	//starter:component

	_as func(certificates.DAO) //starter:as("#")

	Agent       dxo.DatabaseAgent  //starter:inject("#")
	UUIDService random.UUIDService //starter:inject("#")

}

func (inst *CertificateDaoImpl) _impl() certificates.DAO {
	return inst
}

func (inst *CertificateDaoImpl) model() *entity.Certificate {
	return new(entity.Certificate)
}

func (inst *CertificateDaoImpl) listModel() []*entity.Certificate {
	return make([]*entity.Certificate, 0)
}

func (inst *CertificateDaoImpl) makeResult(o *entity.Certificate, res *gorm.DB) (*entity.Certificate, error) {
	err := res.Error
	if err != nil {
		return nil, err
	}
	return o, nil
}

// Find ...
func (inst *CertificateDaoImpl) Find(db *gorm.DB, id dxo.CertificateID) (*entity.Certificate, error) {
	db = inst.Agent.DB(db)
	o1 := inst.model()
	res := db.First(o1, id)
	return inst.makeResult(o1, res)
}

// List ...
func (inst *CertificateDaoImpl) List(db *gorm.DB, query *certificates.Query) ([]*entity.Certificate, error) {

	db = inst.Agent.DB(db)
	if query == nil {
		query = new(certificates.Query)
	}

	list := inst.listModel()
	item := inst.model()
	domain := query.Domain

	finder := new(database.Finder)
	finder.DB = db
	finder.ItemModel = item
	finder.ListModel = &list
	finder.Pagination = &query.Pagination
	finder.QueryString = "dn = ?"
	finder.QueryArgs = []any{domain}

	err := finder.Find()
	if err != nil {
		return nil, err
	}
	return list, nil
}

// Insert ...
func (inst *CertificateDaoImpl) Insert(db *gorm.DB, item *entity.Certificate) (*entity.Certificate, error) {

	uuid := inst.UUIDService.Build().Class("entity.Certificate").Generate()

	item.ID = 0
	item.UUID = uuid

	db = inst.Agent.DB(db)
	res := db.Create(item)
	return inst.makeResult(item, res)
}
